import re
from collections import defaultdict
import os
import csv
from utils import CSVUtils
import json
csvutils = CSVUtils()

class WashLog():
    @staticmethod
    def save_ip_content_to_json(filename, ip_content_list):
        # 如果 ip_content_list 为空，则不进行写入
        if not ip_content_list:
            return
        # 将列表写入到 JSON 文件中
        with open(filename, 'w') as json_file:
            json.dump(ip_content_list, json_file, indent=4,ensure_ascii=False)  # 使用 indent=4 美化格式

    @staticmethod
    def parse_logs(log_file_path):
        fun_set = []
        log_entries = {}
        ip_content_list = []
        with open(log_file_path, 'r') as file:
            for line in file:
                # 跳过包含 "exited with" 和 "killed by" 的行
                if "exited with" in line or "killed by" in line:
                    continue
                """
                匹配未完成的调用
                PID TIMESTAMP FUNCTION(PARAMS <unfinished ...> 
                """
                unfinished_match = re.match(
                    r'(\d+)\s+\d+\.\d+\s+(\w+)\((.*?)(<unfinished \.\.\.>)', line)
                """
                匹配恢复的调用
                PID TIMESTAMP <... FUNCTION resumed> PARAMS [<unfinished ...>] ) = RETURN_VALUE [ (ERROR) ]
                """
                resumed_match = re.match(
                    r'(\d+)\s+\d+\.\d+\s+<\.\.\. (\w+) resumed> (.*?)(<unfinished \.\.\.>)?\)? = (.*)',
                    line)
                """ 
                匹配完整的调用
                PID TIMESTAMP FUNCTION(PARAMS) = RETURN_VALUE [ (ERROR) ]66
                """
                complete_match = re.match(
                    r'(\d+)\s+\d+\.\d+\s+(\w+)\((.*?)\) = (.*)', line)

                if unfinished_match:
                    pid, func, params, _ = unfinished_match.groups()
                    func = re.sub(r'[^a-zA-Z]', '', func)
                    if pid not in log_entries:
                        log_entries[pid] = []
                    log_entries[pid].append((func, params))

                elif resumed_match:
                    content = ""
                    pid, func, params, unfinished, retval = resumed_match.groups()
                    func = re.sub(r'[^a-zA-Z]', '', func)
                    if unfinished:
                        continue
                    # syscall_count[func] += 1
                    if pid in log_entries and log_entries[pid]:
                        func_prev, params_prev = log_entries[pid].pop()
                        params = f"{params_prev}{params}"
                        if "UNIX" not in params:
                            if func in [
                                    'sendmsg', 'sendto', 'recvfrom', 'recvmsg'
                            ]:
                                ip_list, is_net = csvutils.find_ip(func, params)
                                if is_net:
                                    content = csvutils.find_params_content(params)
                                    ip_content_list.append({
                            "funtion": func,
                            "ip_list": ip_list,
                            "content": content
                                                })
                        params = params.replace(" ", "")
                        retval = retval.replace(" ", "")
                        fun_set.append(
                            (pid, func, params, content, retval))  # 使用元组来存储信息

                elif complete_match:
                    content = ""
                    pid, func, params, retval = complete_match.groups()
                    func = re.sub(r'[^a-zA-Z]', '', func)
                    # syscall_count[func] += 1
                    if "UNIX" not in params:
                        if func in ['sendmsg', 'sendto', 'recvfrom', 'recvmsg']:
                            ip_list,is_net = csvutils.find_ip(func, params)
                            if is_net:
                                content = csvutils.find_params_content(params)
                                ip_content_list.append({
                            "funtion": func,
                            "ip_list": ip_list,
                            "content": content
                                                })
                    params = params.replace(" ", "")
                    retval = retval.replace(" ", "")
                    fun_set.append(
                        (pid, func, params, content, retval))  # 使用元组来存储信息
        return fun_set , ip_content_list


# directory = '/var/dataset/goodware/'

# for filename in os.listdir(directory):
#     if filename.endswith("strace"):
#         fs = []
#         file_path = os.path.join(directory, filename)
#         if os.path.isfile(file_path):
#             fs= parse_logs(file_path)
#             output_file_path = f'/var/dataset/goodware/logcsv/{filename}.csv'
#             with open(output_file_path, 'w') as output_file:
#                 csv_writer = csv.writer(output_file)
#                 csv_writer.writerow(["PID", "Function", "Params", "Result"])
#                 # Writing the parsed log entries into the CSV
#                 for entry in fs:
#                     csv_writer.writerow([entry[0], entry[1], entry[2], entry[3]])
#             os.remove(file_path)
#         print(filename)


# log_file = '/home/chenjiaxiong/jx_code/a957fc570681879469a0b061a566aa80.strace'
# fs = []
# fs , ip_content_list= parse_logs(log_file)
# # Writing to CSV instead of a plain text file
# csv_output_file_path = '/home/chenjiaxiong/jx_code/a957fc570681879469a0b061a566aa80.csv'
# with open(csv_output_file_path, mode='w', newline='') as csv_file:
#     csv_writer = csv.writer(csv_file)

#     # Writing the header row
#     csv_writer.writerow(["PID", "Function", "Params", "Content","Result"])

#     # Writing the parsed log entries into the CSV
#     for entry in fs:
#         csv_writer.writerow([entry[0], entry[1], entry[2], entry[3] , entry[4]])

# # 保存 IP 和内容到 JSON
# json_output_file = f'/home/chenjiaxiong/jx_code/a957fc570681879469a0b061a566aa80.json'
# save_ip_content_to_json(json_output_file, ip_content_list)